/*
 * Developer : Jack Matthews
 * Email: developer@droidprofessor.com
 * 
 * Copyright (C) 2010 http://droidprofessor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.droidprofessor.android.library.phonelicenses;

import com.droidprofessor.android.library.phonelicenses.R;
import com.droidprofessor.android.licensegenerator.client.AndroidClientLicenseImpl;
import com.droidprofessor.licensegenerator.lib.Feature;

import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalPayment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.Toast;

public class ActivityPayment extends Activity implements android.view.View.OnClickListener {
	private static final String TAG = "ActivityActivate";

	//Views
	private Button btnLicense, btnConditions,btnRefundPolicy;
	private CheckBox chkLicense,chkConditions,chkRefunds;
	private LinearLayout llPaymentButton;
	private TableLayout tableLayoutAgreementControls;
	
	private PaymentMethodButton paymentMethodButton;
	private ApplicationDataCache.PaymentMethod paymentMethod;
	private Handler handler;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
        // Request for the progress bar to be shown in the title
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.com_phonelicenses_payment);
		getControls();
		handler = new Handler();
		setupPaymentMethod();
	}

	
	
	private void setupPaymentMethod() {
		String refName = getIntent().getExtras().getString("refName");
		this.paymentMethod = ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(refName);

		if( refName.equals(ApplicationDataCache.PaymentMethod.REFNAME_PAYPAL_INTEGRATED) )
			this.paymentMethodButton = new PayPalIntegratedPayment();
		else if( refName.equals(ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED) )
			this.paymentMethodButton = new AndroidMarketPayment();
		else
			this.paymentMethodButton = new HtmlPayment();
		
	}
	

	@Override
	protected void onResume() {
		super.onResume();
		updateVisibleControls();
	}
	


	@Override
	protected void onDestroy() {
		super.onDestroy();
		
//		//Null out items that may have a reference to our context
//		if(paidAlreadyDialog!=null)
//			if(paidAlreadyDialog.isShowing())
//				paidAlreadyDialog.cancel();
//		
//		paidAlreadyDialog=null;
		
		this.paymentMethodButton.onDestroy();
	}






	/**
	 * Get hold of our views
	 */
	private void getControls() {
		btnLicense = (Button)findViewById(R.id.button_license); 
		btnConditions = (Button)findViewById(R.id.button_conditions); 
		btnRefundPolicy = (Button)findViewById(R.id.button_refund); 
		tableLayoutAgreementControls = (TableLayout)findViewById(R.id.agreementControls);
		
		chkLicense =  (CheckBox)findViewById(R.id.checkbox_agree_license);
		chkConditions =  (CheckBox)findViewById(R.id.checkbox_agree_conditions);
		chkRefunds =  (CheckBox)findViewById(R.id.checkbox_agree_refund);

		llPaymentButton = (LinearLayout)findViewById(R.id.llPaymentButton);
		
		btnLicense.setOnClickListener(this);
		btnConditions.setOnClickListener(this);
		btnRefundPolicy.setOnClickListener(this);
	}





	/**
	 * Update the payment controls depending on the state of
	 * the is_verified preference
	 */
	private void updateVisibleControls() {
//		boolean verifiedAccount = PreferencesHelper.isAccountVerified(this);
//		
//		
//		if( verifiedAccount ) {
//			displayPaidAlreadyMessage();
//		} 
		
		//Add the button
		paymentMethodButton.loadPaymentButton();
	}
	
	
	/**
	 * Call this when adding children
	 * 
	 * @param child
	 */
	private void displayPaymentButton(View child) {
		llPaymentButton.removeAllViews(); //clear out children in case of lost focus
		llPaymentButton.addView(child);
	}
	
	
//	private boolean paidAlreadyMessageDisplayed = false;
//	private AlertDialog paidAlreadyDialog;
//	private void displayPaidAlreadyMessage() {
//		if( !this.paidAlreadyMessageDisplayed ) {
//			paidAlreadyDialog = new AlertDialog.Builder(this)
//				.setIcon(android.R.drawable.ic_dialog_alert)
//				.setTitle( R.string.com_phonelicenses_already_paid )
//				.setMessage( R.string.com_phonelicenses_already_paid_message )
//				.setPositiveButton(R.string.com_phonelicenses_ok, null)
//				.show();
//			
//			this.paidAlreadyMessageDisplayed = true;
//		}
//	}





	@Override
	public void onClick(View v) {
		Intent intent;
		
		switch (v.getId()) {
			
			case R.id.button_conditions:
				//Add enabled Features only
				String conditionsFormat = getString(R.string.com_phonelicenses_condition_disclaimer);
				StringBuilder licenseContents = new StringBuilder();
				for( Feature f : Feature.getEnabledFeatures() ) {
					//Don't show these
					if(f == Feature.APPLICATION_ID || f == Feature.LICENSING_SYSTEM || f == Feature.TIMESTAMP)
						continue;
						
					licenseContents
						.append("<h4>").append(f.getKey()).append("</h4>")
						.append(f.getValue());
				}
				String conditionsString = String.format(conditionsFormat, licenseContents);
				
				//open the Activity
				intent = new Intent(this, ActivityViewText.class);
				intent.setAction(Intent.ACTION_VIEW);
				intent.putExtra(ActivityViewText.EXTRA_CONTENT, conditionsString);
				startActivity(intent);	
				break;
				
			case R.id.button_license:
				intent = new Intent(this, ActivityViewText.class);
				intent.setAction(Intent.ACTION_VIEW);
				intent.putExtra(ActivityViewText.EXTRA_CONTENT, ApplicationDataCache.getInstance().getLicenseAgreement() );
				startActivity(intent);		
				break;
			
			case R.id.button_refund:
				intent = new Intent(this, ActivityViewText.class);
				intent.setAction(Intent.ACTION_VIEW);
				intent.putExtra(ActivityViewText.EXTRA_CONTENT, ApplicationDataCache.getInstance().getRefundPolicy() );
				startActivity(intent);		
				break;
		}
		
		this.paymentMethodButton.onClick(v);

	}
	
	
	
	/**
	 * Accept the license agreement
	 * 
	 * @return true on checked
	 */
	private boolean acceptsLicense() {
		boolean checked = this.chkLicense.isChecked();
		if(!checked) Toast.makeText(this, R.string.com_phonelicenses_must_agree_license, Toast.LENGTH_SHORT).show();
		return checked;
	}


	/**
	 * Accept the conditions
	 * 
	 * @return true on checked
	 */
	private boolean acceptsConditions() {
		boolean checked = this.chkConditions.isChecked();
		if(!checked) Toast.makeText(this, R.string.com_phonelicenses_must_agree_conditions, Toast.LENGTH_SHORT).show();
		return checked;
	}
	
	
	/**
	 * Accept refund policy
	 * 
	 * @return true on checked
	 */
	private boolean acceptsRefundPolicy() {
		boolean checked = this.chkRefunds.isChecked();
		if(!checked) Toast.makeText(this, R.string.com_phonelicenses_must_agree_refund_policy, Toast.LENGTH_SHORT).show();
		return checked;
	}

	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		this.paymentMethodButton.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	
	
	
	
	
//	private String getJoomlaBaseUrl() {
//		return 
//			"http://"+
//			AndroidClientLicenseImpl.getInstance().getHost()+
//			":"+AndroidClientLicenseImpl.getInstance().getPort()+
//			"/"+
//			AndroidClientLicenseImpl.getInstance().getPath();
//	}
//	
//	
//	
//	/**
//	 * Gets the URL for the IPN depending on the controller name
//	 * 
//	 * @param controller
//	 * @return the notification URL
//	 */
//	private String getNotifyUrl(String controller) {
//		String url =  
//			getJoomlaBaseUrl()+
//			"?option=com_phonelicenses"+
//			"&controller="+controller+
//			"&format=raw";
//		Log.d(TAG, "NotifyUrl: "+url);
//		return url;
//	}
//
//	
//	private String getPaymentReturnUrl(String layout) {
//		String url = 
//			getJoomlaBaseUrl()+
//			"?option=com_phonelicenses"+
//			"&controller=ipn"+
//			"&view=ipn"+
//			"&format=html"+
//			"&layout="+layout
//			;
//		Log.d(TAG, layout+": "+url);
//		return url;
//	}
	
	
	
	
//	/**
//	 * Adds queries to the query string while doing some validation
//	 * 
//	 * @param essential is this element absolutely essential, thus throwing an IllegalStateException if empty
//	 * @param value the container List holding the query string
//	 * @param key the key
//	 * @param query the value
//	 */
//	private void addQuery(boolean essential, List<NameValuePair> query, String key, String value) {
//		boolean valid = true;
//		
//		if( value == null || value.equals("") )
//			valid=false;
//		
//		if(essential && !valid )
//			throw new IllegalStateException(key+" is essential and cannot be null or empty");
//		
//		if(valid)
//			query.add(new BasicNameValuePair(key, value )); 
//	}
	
	
	
//	private class PayPalWebBrowserPayment implements PaymentProvider {
//
//		private ImageButton paymentButton;
//		
//		@Override
//		public void display() {
//			if(paymentButton==null) {
//				paymentButton = new ImageButton(ActivityActivate.this);
//				paymentButton.setBackgroundResource(R.drawable.com_phonelicenses_androidmarket_logo);
//				paymentButton.setOnClickListener(ActivityActivate.this);
//		    	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//				params.setMargins(0, 0, 0, 10);
//		    	paymentButton.setLayoutParams(params);
//				llPaymentButtons.addView(paymentButton);
//			}
//		}
//
//
//		
//		@Override
//		public void loadPaymentProvider() {
//			/*
//			 * Account details have already been verified so
//			 * send the user to paypal
//			 */
//			new AlertDialog.Builder(ActivityActivate.this)
//			.setIcon(R.drawable.com_phonelicenses_androidmarket_logo)
//			.setMessage(R.string.com_phonelicenses_go_to_paypal_notification)
//			.setPositiveButton(R.string.com_phonelicenses_ok, new LoadBrowser())
//			.setNegativeButton(R.string.com_phonelicenses_cancel, null)
//			.show();
//		}
//		
//		
//		
//		/**
//		 * 
//		 * Open up a browser and go to the paypal site.
//		 * 
//		 * @author Jack Matthews
//		 *
//		 */
//		private final class LoadBrowser implements OnClickListener {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				
//				String host = XmlTags.getAppTag(XmlTags.TAG_PAYPAL_WEBSITE_HOST);
//					
//				//Form the URL
//				List<NameValuePair> query = new ArrayList<NameValuePair>();
//				query.add(new BasicNameValuePair("custom", generateApplicationIdUsernameString() ));
//				query.add(new BasicNameValuePair("cmd", "_xclick" ));
//				query.add(new BasicNameValuePair("business", XmlTags.getAppTag(XmlTags.TAG_PAYPAL_MERCHANT_EMAIL) ));
//				query.add(new BasicNameValuePair("item_name", XmlTags.getAppTag(XmlTags.TAG_APPLICATION_NAME) ));
//				query.add(new BasicNameValuePair("amount", XmlTags.getAppTag(XmlTags.TAG_PAYPAL_PRICE) ));
//				query.add(new BasicNameValuePair("currency_code", XmlTags.getAppTag(XmlTags.TAG_PAYPAL_CURRENCY) ));
//				query.add(new BasicNameValuePair("notify_url", getNotifyUrl("paypal") ));
//				query.add(new BasicNameValuePair("return", getPaymentReturnUrl("success") ));
//				query.add(new BasicNameValuePair("cancel_return", getPaymentReturnUrl("cancel") ));			
////				query.add(new BasicNameValuePair("image_url", custom ));
////				query.add(new BasicNameValuePair("cpp_header_image", custom ));
////				query.add(new BasicNameValuePair("lc", custom ));				
//				query.add(new BasicNameValuePair("email", PreferencesHelper.getEmail(getApplicationContext()) ));
//				
//				String firstName = PreferencesHelper.getName(getApplicationContext()).split(" +")[0];
//				if( !firstName.equals(""))
//					query.add(new BasicNameValuePair("first_name", firstName));
//				
//
//				
//				URI uri;
//				try {
//					uri = URIUtils.createURI("https", host, -1, "cgi-bin/webscr", URLEncodedUtils.format(query, HTTP.UTF_8), null);
//					
//				} catch (URISyntaxException e) {
//					if(Logging.ERROR) {
//						Log.e(TAG, "The Paypal URI could not be formed");
//						e.printStackTrace();
//					}
//					throw new IllegalStateException("The Paypal URI could not be formed");
//				}				
//				
//				//open the browser
//				Uri u = Uri.parse(uri.toString());
//				Log.d(TAG, "Go to paypal: "+u );
//				Intent i = new Intent(Intent.ACTION_VIEW, u);
//				startActivity(i);
//			}
//		}
//
//
//
//		@Override
//		public void onActivityResult(int requestCode, int resultCode,
//				Intent data) {
//			
//		}
//
//		@Override
//		public void onClick(View v) {
//			if( v == this.paymentButton )
//				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() )
//					loadPaymentProvider();	
//		}
//
//
//		@Override
//		public void onDestroy() {
//			
//		}
//		
//	}
	
	
	
	
	
	
	
	
	
	
	
	
//	private class PayPalIntegratedPayment implements PaymentProvider {
//
//		private PayPal ppObj;
//		private ProgressDialog progressDialog;
//		private Button payPalButton;
//		
//		
//		@Override
//		public void display() {
//			if(ppObj==null) getPaypalButton(); //load the paypal library
//		}
//
//
//		@Override
//		public void loadPaymentProvider() {
//			
//		}
//		
//		@Override
//		public void onActivityResult(int requestCode, int resultCode,
//				Intent data) {
//			switch (requestCode) {
//				case PhoneLicensesCodes.REQUEST_CODE_PAYPAL_INTEGRATED:
//					doPaymentResult(resultCode, data);
//					break;
//				}
//
//		}
//		
//		
//		
//		/**
//		 * Create a new PayPal Payment
//		 */
//		private void paymentPayPalIntegrated() {
//			//Our cached preferences hold the amounts
//			float amount = Float.parseFloat(XmlTags.getAppTag(XmlTags.TAG_PAYPAL_PRICE));
//			String currency = XmlTags.getAppTag(XmlTags.TAG_PAYPAL_CURRENCY);
//			String merchant = XmlTags.getAppTag(XmlTags.TAG_PAYPAL_MERCHANT_EMAIL);
//			String memo = generateApplicationIdUsernameString(); //need to pass custom through the memo field for the API
//			String merchantName = XmlTags.getAppTag(XmlTags.TAG_MERCHANT_NAME);
//		
//			PayPalPayment newPayment = new PayPalPayment();
//			newPayment.setAmount(amount);
//			newPayment.setCurrency(currency);
//			newPayment.setRecipient(merchant);
//			newPayment.setItemDescription(memo);
//			newPayment.setMerchantName(merchantName);
//
//			Intent checkoutIntent = new Intent(ActivityActivate.this, PayPalActivity.class);
//			checkoutIntent.putExtra(PayPalActivity.EXTRA_PAYMENT_INFO, newPayment);
//			startActivityForResult(checkoutIntent, PhoneLicensesCodes.REQUEST_CODE_PAYPAL_INTEGRATED);
//			
//			Log.d(TAG, "Started PayPal Activity");
//		}
//		
//		
//		
//		private void doPaymentResult(int resultCode, Intent data) {
//			Log.d(TAG, "PayPal Activity Response Recieved");
//			
//			switch (resultCode) {
//				case Activity.RESULT_OK:
//					Log.d(TAG, "Payment Succeded");
//					String transactionId = data.getStringExtra(PayPalActivity.EXTRA_TRANSACTION_ID);
//					AndroidClientLicenseImpl.getInstance().downloadAndInstallLicense(getApplicationContext());
//					
//					PreferencesHelper.setPaymentVerified(ActivityActivate.this);
//					PreferencesHelper.setTransactionNo(ActivityActivate.this, transactionId);
//					
//					ActivityActivate.this.finish();
//	
//					break;
//				case Activity.RESULT_CANCELED:
//					Log.d(TAG, "Payment Cancelled");
//					Utils.showDialogMessage(ActivityActivate.this, R.string.com_phonelicenses_transaction_canceled);
//					break;
//					
//				case PayPalActivity.RESULT_FAILURE:
//					Log.d(TAG, "Payment Failed");
//					//String errorId = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
//					String errorMsg = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
//					Utils.showDialogMessage(ActivityActivate.this, errorMsg);
//					break;
//					
//				default:
//					break;
//			}
//			
//		}
//
//		
//		
//		private InitAndroidIntegratedPayPal background;
//		/**
//		 * Get a PayPal button from the PayPal Server
//		 */
//		private void getPaypalButton() {
//	    	//display a progress dialog to the user
//	    	progressDialog = new ProgressDialog( ActivityActivate.this );
//	    	progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//	    	progressDialog.setMessage("Loading PayPal Payment Library");
//	    	progressDialog.setCancelable(false);
//	    	progressDialog.show();
//		
//	    	background = new InitAndroidIntegratedPayPal();
//	    	background.execute();
//		}
//		
//		
//		
//		/**
//		 * Send a request to the PayPal server to init() a new 
//		 * PayPal button
//		 * 
//		 * @author Jack Matthews
//		 *
//		 */
//		private class InitAndroidIntegratedPayPal extends AsyncTask<Void, Void, Boolean> {
//
//			@Override
//			protected Boolean doInBackground(Void... params) {
//				
//				//Get values from preferences
//				String apiKey = XmlTags.getAppTag(XmlTags.TAG_PAYPAL_ANDROID_APPKEY);
//				int env = Integer.valueOf(XmlTags.getAppTag(XmlTags.TAG_PAYPAL_ENVIRONMENT));
//				
//				//initialize paypal
//				if (ppObj == null) ppObj = PayPal.initWithAppID(
//							getBaseContext(), 
//							apiKey, 
//							env
//							);
//				
//				return true;
//			}
//
//			@Override
//			protected void onPostExecute(Boolean result) {
//				//Paypal button
//				payPalButton = ppObj.getPaymentButton(PayPal.BUTTON_194x37, ActivityActivate.this, PayPal.PAYMENT_TYPE_HARD_GOODS);
//				payPalButton.setOnClickListener(ActivityActivate.this);
//				llPaymentButtons.addView(payPalButton);
//				
//				progressDialog.dismiss();
//				
//				Log.d(TAG, "PayPal Button Setup Complete");
//			}
//
//			@Override
//			protected void onProgressUpdate(Void... values) {
//
//			}
//			
//		}
//
//
//
//		@Override
//		public void onClick(View v) {
//			if(v == payPalButton)
//				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() )
//					paymentPayPalIntegrated();
//		}
//
//		@Override
//		public void onDestroy() {
//			
//			if(progressDialog!=null)
//				if(progressDialog.isShowing())
//					progressDialog.cancel();
//				
//			if(background!=null)
//				background.cancel(true);
//		}
//
//		
//	}
	
	
	
	
	
	
	
	
	
	
	
//	private class OneBipWebBrowserPayment implements PaymentProvider {
//
//		private ImageButton paymentButton;
//		
//		@Override
//		public void display() {
//			if(paymentButton==null) {
//				paymentButton = new ImageButton(ActivityActivate.this);
//				paymentButton.setBackgroundResource(R.drawable.com_phonelicenses_androidmarket_logo);
//				paymentButton.setOnClickListener(ActivityActivate.this);
//		    	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//				params.setMargins(0, 0, 0, 10);
//		    	paymentButton.setLayoutParams(params);
//				llPaymentButtons.addView(paymentButton);
//			}
//		}
//
//		
//		@Override
//		public void loadPaymentProvider() {
//			showPaypalWebsiteRedirectionDialog();
//		}
//		
//		
//		
//		/**
//		 * Confirm Dialog
//		 */
//		private void showPaypalWebsiteRedirectionDialog() {
//			new AlertDialog.Builder(ActivityActivate.this)
//			.setIcon(R.drawable.com_phonelicenses_androidmarket_logo)
//			.setMessage(R.string.com_phonelicenses_go_to_onebip_notification)
//			.setPositiveButton(R.string.com_phonelicenses_ok, new OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					loadBrowser();	
//				}
//			})
//			.setNegativeButton(R.string.com_phonelicenses_cancel, null)
//			.show();
//		}
//		
//		
//		
//		private void loadBrowser() {
//			//Form the URL
//			List<NameValuePair> query = new ArrayList<NameValuePair>();
//			
//			addQuery(true, query, "command", "express_pay");
//			addQuery(true, query, "username", XmlTags.getAppTag(XmlTags.TAG_ONEBIP_USERNAME) );
//			addQuery(true, query, "item_name", XmlTags.getAppTag(XmlTags.TAG_APPLICATION_NAME) );
//			addQuery(true, query, "description", XmlTags.getAppTag(XmlTags.TAG_APPLICATION_NAME) );
//			addQuery(true, query, "price", XmlTags.getAppTag(XmlTags.TAG_ONEBIP_PRICE) );
//			addQuery(true, query, "currency", XmlTags.getAppTag(XmlTags.TAG_ONEBIP_CURRENCY) );
//			addQuery(false, query, "lang", Locale.getDefault().getLanguage());	
//			addQuery(true, query, "return_url", getPaymentReturnUrl("success") );
//			addQuery(true, query, "cancel_url", getPaymentReturnUrl("cancel") );
//			addQuery(true, query, "notify_url", getNotifyUrl("onebip") );
//			addQuery(false, query, "support_email", XmlTags.getAppTag(XmlTags.TAG_SUPPORT_EMAIL ) );
//			addQuery(true, query, "custom[idusername]", generateApplicationIdUsernameString() );
//			addQuery(false, query, "customer_email", PreferencesHelper.getEmail(getApplicationContext()) );
//			addQuery(false, query, "customer_firstname", PreferencesHelper.getName(getApplicationContext()) );
//			addQuery(false, query, "customer_cell", getLine1Number() );
//			//addQuery(true, query, "customer_country", Locale.getDefault().getCountry() );
//			addQuery(false, query, "logo_url", XmlTags.getAppTag(XmlTags.TAG_ONEBIP_LOGO_URL) );
//
//			
//			URI uri;
//			try {
//				uri = URIUtils.createURI("https", "www.onebip.com", -1, "otms/", URLEncodedUtils.format(query, HTTP.UTF_8), null);
//				
//			} catch (URISyntaxException e) {
//				if(Logging.ERROR) {
//					Log.e(TAG, "The Paypal URI could not be formed");
//					e.printStackTrace();
//				}
//				throw new IllegalStateException("The Paypal URI could not be formed");
//			}
//
//			
//			//open the browser
//			Uri u = Uri.parse(uri.toString());
//			Log.d(TAG, "Go to onebip: "+u );
//			Intent i = new Intent(Intent.ACTION_VIEW, u);
//			startActivity(i);
//		}
//
//		
//		
//		private String getLine1Number() {
//			TelephonyManager mTelephonyMgr = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
//			return mTelephonyMgr.getLine1Number();
//		}
//
//		
//		
//		@Override
//		public void onActivityResult(int requestCode, int resultCode,
//				Intent data) {
//			
//		}
//
//		@Override
//		public void onClick(View v) {
//			if( v == this.paymentButton )
//				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() )
//					loadPaymentProvider();	
//		}
//
//
//		@Override
//		public void onDestroy() {
//			
//		}
//		
//	}
	
	
	
	
	
	
	
	
	
	
	
//	private class GoogleCheckoutWebBrowserPayment implements PaymentProvider {
//
//		private WebView browser = null;
//		
//		
//		/**
//		 * Interface for Javascript communication
//		 */
//		private class JavascriptInterface {
//			
//			//This is in fact used but from JavaScript
//			@SuppressWarnings("unused")
//			public boolean checkboxPass() {
//				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() ) {
//					handler.post(new Runnable() {
//						
//						@Override
//						public void run() {
//							browser.setBackgroundResource(R.color.com_phonelicenses_white);							
//						}
//					});
//					
//					return true;
//				}
//				return false;
//			}
//		}
//		
//		@Override
//		public void display() {
//			if(browser==null) {
//				
//				String host = XmlTags.getAppTag(XmlTags.TAG_GOOGLECHECKOUT_WEBSITE_HOST);
//				String merchantId = XmlTags.getAppTag(XmlTags.TAG_GOOGLECHECKOUT_ID);
//				String item_name_1 = XmlTags.getAppTag(XmlTags.TAG_GOOGLECHECKOUT_ITEM_NAME);
//				String item_price_1 = XmlTags.getAppTag(XmlTags.TAG_GOOGLECHECKOUT_PRICE);
//				String item_currency_1 = XmlTags.getAppTag(XmlTags.TAG_GOOGLECHECKOUT_CURRENCY);
//				String private_item_data = generateApplicationIdUsernameString();
//
//
//				String form = String.format(getString(R.string.com_phonelicenses_googlecheckout_html_button), 
//						host,
//						merchantId,
//						item_name_1,
//						item_price_1,
//						item_currency_1,
//						private_item_data
//						);
//				
//				Log.d(TAG, form);
//		    	
//				browser = new WebView(ActivityActivate.this);
//				browser.setBackgroundColor(0);
//				browser.getSettings().setJavaScriptEnabled(true);
//				browser.addJavascriptInterface(new JavascriptInterface(), "javaInterface");
//				browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//				browser.getSettings().setSupportZoom(true);
//
//				
////				browser.setWebViewClient(new WebViewClient() {
////					@Override
////					public boolean shouldOverrideUrlLoading(WebView view,
////							String url) {
////						Intent i = new Intent(Intent.ACTION_VIEW);
////						i.setData(Uri.parse(url));
////						startActivity(i);
////						Log.d(TAG, "executing: shouldOverrideUrlLoading()");
////						return true;
////					}
////
////				});
//				
//				
//				//browser.getSettings().setLoadsImagesAutomatically(true);
//				
//				//browser.loadData(form, "text/html", "UTF-8");				
//				browser.loadDataWithBaseURL("https://checkout.google.com", form, "text/html", "UTF-8", null);
//				llPaymentButtons.addView(browser);
//			}
//		}
//
//		
//		@Override
//		public void loadPaymentProvider() {
//
//		}
//
//
//
//		@Override
//		public void onActivityResult(int requestCode, int resultCode,
//				Intent data) {
//			
//		}
//
//		@Override
//		public void onClick(View v) {
//	
//		}
//
//
//		@Override
//		public void onDestroy() {
//			
//		}
//		
//	}
	
	
	
	
	
	private String dialogMessage = "";
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_MESSAGE:
			dialog = new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(dialogMessage)
			.setPositiveButton(R.string.com_phonelicenses_ok, null)
			.create();
			break;

		default:
			dialog = null;
			break;
		}
		
		return dialog;
	}



	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);
	}
	
	
	
	private void showMessageDialog(String message) {
		this.dialogMessage = message;
		showDialog(PhoneLicensesCodes.DIALOG_MESSAGE);
	}

	private void showMessageDialog(int message) {
		this.dialogMessage = getString(message);
		showDialog(PhoneLicensesCodes.DIALOG_MESSAGE);
	}






	/**
	 * For Website HTML Form payments
	 * 
	 * @author Jack Matthews
	 *
	 */
	public class HtmlPayment implements PaymentMethodButton {
		private WebView browser = null;
		
		/**
		 * Interface for Javascript communication
		 */
		private class JavascriptInterface {
			
			//This is in fact used but from JavaScript
			@SuppressWarnings("unused")
			public boolean checkboxPass() {
				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() ) {
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							browser.setBackgroundResource(R.color.com_phonelicenses_white);
							
							//allow the browser to take up the full screen
							tableLayoutAgreementControls.setVisibility(View.GONE);
							
							//change the txt
							
						}
					});
					
					return true;
				}
				return false;
			}
		}
		
		
		@Override
		public void loadPaymentButton() {
			
			if(browser==null) {
				String f = "";
				try {
					f = paymentMethod.getHtmlButton(ActivityPayment.this);
				} catch (IllegalAccessException e) {
					Log.e(TAG, e.getMessage(), e);
					showMessageDialog("An error occurred while creating the View for this payment method");
					ActivityPayment.this.finish();
					return;
				}
				
				//Create a valid HTML document
				String form = String.format(getString(R.string.com_phonelicenses_html_button_template), getString(R.string.com_phonelicenses_press_the_button_for_payment),f);
				
				Log.d(TAG, form);
				browser = new WebView(ActivityPayment.this);
				browser.setBackgroundColor(0);
				browser.getSettings().setJavaScriptEnabled(true);
				browser.addJavascriptInterface(new JavascriptInterface(), "javaInterface");
				browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
				browser.getSettings().setSupportZoom(true);
				//browser.loadData("<p>Some test HTML</p>", "text/html", "UTF-8"); //This does not work for some reason
				browser.loadDataWithBaseURL(ApplicationDataCache.getInstance().getBaseUrl(), form, "text/html", "UTF-8", null);
			}
			
			displayPaymentButton(browser);
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			//nothing to do
		}

		@Override
		public void onClick(View v) {
			//nothing to do
		}

		@Override
		public void onDestroy() {
			//nothing to do
		}
		
	}
	
	
	
	
	
	/**
	 * An Integrated PayPal Button
	 * 
	 * @author Jack Matthews
	 *
	 */
	public class PayPalIntegratedPayment implements PaymentMethodButton {
		private static final String TAG = "PayPalIntegratedPayment";
		private PayPal ppObj;
		private ProgressDialog progressDialog;
		private Button payPalButton;
		private InitAndroidIntegratedPayPal background;
		
		/**
		 * Create a new PayPal Payment
		 */
		private void paymentPayPalIntegrated() {
			//Our cached preferences hold the amounts
			float amount = Float.parseFloat( paymentMethod.getPrice() );
			String currency = paymentMethod.getCurrency();
			String merchant = paymentMethod.getExtra("paypalMerchantEmail");
			String memo = AndroidClientLicenseImpl.getInstance().getApplicationId()+":"+PreferencesHelper.getUsername(ActivityPayment.this); //need to pass custom through the memo field for the API
			String merchantName = ApplicationDataCache.getInstance().getMerchantName();
		
			PayPalPayment newPayment = new PayPalPayment();
			newPayment.setAmount(amount);
			newPayment.setCurrency(currency);
			newPayment.setRecipient(merchant);
			newPayment.setItemDescription(memo);
			newPayment.setMerchantName(merchantName);

			Intent intent = new Intent(ActivityPayment.this, PayPalActivity.class);
			intent.putExtra(PayPalActivity.EXTRA_PAYMENT_INFO, newPayment);
			startActivityForResult(intent, PhoneLicensesCodes.REQUEST_CODE_PAYPAL_INTEGRATED);
			
			Log.d(TAG, "Started PayPal Activity");
		}
		
		
		private void doPaymentResult(int resultCode, Intent data) {
			Log.d(TAG, "PayPal Activity Response Recieved");
			
			switch (resultCode) {
				case Activity.RESULT_OK:
					Log.d(TAG, "Payment Succeded");
					String transactionId = data.getStringExtra(PayPalActivity.EXTRA_TRANSACTION_ID);
					AndroidClientLicenseImpl.getInstance().downloadAndInstallLicense(getApplicationContext());
					
					PreferencesHelper.setPaymentVerified(ActivityPayment.this);
					PreferencesHelper.setTransactionNo(ActivityPayment.this, transactionId);
					
					ActivityPayment.this.finish();
	
					break;
				case Activity.RESULT_CANCELED:
					Log.d(TAG, "Payment Cancelled");
					showMessageDialog(R.string.com_phonelicenses_transaction_canceled);
					break;
					
				case PayPalActivity.RESULT_FAILURE:
					Log.d(TAG, "Payment Failed");
					String errorMsg = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
					showMessageDialog(errorMsg);
					break;
					
				default:
					break;
			}
			
		}
		
		
		/**
		 * Get a PayPal button from the PayPal Server
		 */
		private void getPaypalButton() {
	    	//display a progress dialog to the user
	    	progressDialog = new ProgressDialog( ActivityPayment.this );
	    	progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    	progressDialog.setMessage("Loading PayPal Payment Library");
	    	progressDialog.setCancelable(false);
	    	progressDialog.show();
		
	    	background = new InitAndroidIntegratedPayPal();
	    	background.execute();
		}
		
		@Override
		public void loadPaymentButton() {
			if(ppObj==null) {
				getPaypalButton(); //load the paypal library
			} else {
				//the button exists already
				displayPaymentButton(payPalButton);
			}
			
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			switch (requestCode) {
			case PhoneLicensesCodes.REQUEST_CODE_PAYPAL_INTEGRATED:
				doPaymentResult(resultCode, data);
				break;
			}
			
		}

		@Override
		public void onClick(View v) {
			if(v == payPalButton)
				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() )
					paymentPayPalIntegrated();
			
		}

		@Override
		public void onDestroy() {
			if(progressDialog!=null)
				if(progressDialog.isShowing())
					progressDialog.cancel();
				
			if(background!=null)
				background.cancel(true);
			
		}
		
		
		/**
		 * Send a request to the PayPal server to init() a new 
		 * PayPal button
		 * 
		 * @author Jack Matthews
		 *
		 */
		private class InitAndroidIntegratedPayPal extends AsyncTask<Void, Void, Boolean> {

			@Override
			protected Boolean doInBackground(Void... params) {
				
				//Get values from preferences
				String apiKey = paymentMethod.getExtra("paypalAndroidAppkey");
				int env = Integer.valueOf(paymentMethod.getExtra("paypalMode"));
				
				//initialize paypal
				if (ppObj == null) ppObj = PayPal.initWithAppID(
							ActivityPayment.this.getBaseContext(), 
							apiKey, 
							env
							);
				
				return true;
			}

			 
			@Override
			protected void onPostExecute(Boolean result) {
				//Paypal button
				payPalButton = ppObj.getPaymentButton(PayPal.BUTTON_194x37, ActivityPayment.this, PayPal.PAYMENT_TYPE_HARD_GOODS);
				payPalButton.setOnClickListener(ActivityPayment.this);				
				displayPaymentButton(payPalButton);
				progressDialog.dismiss();
				
				Log.d(TAG, "PayPal Button Setup Complete");
			}

			@Override
			protected void onProgressUpdate(Void... values) {

			}
			
		}
		
	}

	
	
	
	
	
	
	
	
	
	
	
	public class AndroidMarketPayment implements PaymentMethodButton {
		Button button;
		
		@Override
		public void loadPaymentButton() {
			button = new Button(ActivityPayment.this);
			button.setText(R.string.com_phonelicenses_get_my_license);
			//button.setBackgroundResource(R.drawable.com_phonelicenses_androidmarket_logo);
			button.setOnClickListener(ActivityPayment.this);
	    	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			
	    	params.setMargins(0, 0, 0, 10);
			button.setLayoutParams(params);
			button.setGravity(Gravity.CENTER_HORIZONTAL);
			
			displayPaymentButton(button);
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			if(requestCode == PhoneLicensesCodes.REQUEST_CODE_ANDROIDMARKET_PAYMENT) {
				String message = data.getStringExtra("message");
				
				switch (resultCode) {
				case PhoneLicensesCodes.RESULT_CODE_ERROR:
					Log.e(TAG, "RESULT_CODE_ERROR: "+message);
					showMessageDialog(message);
					break;
				case PhoneLicensesCodes.RESULT_CODE_DONT_ALLOW:
					Log.w(TAG, "RESULT_CODE_DONT_ALLOW: "+message);
					showMessageDialog(message);
					break;
				case PhoneLicensesCodes.RESULT_CODE_LICENSE_CREATED:
					//Download the license
					AndroidClientLicenseImpl.getInstance().downloadAndInstallLicense(getApplicationContext());

					//Show a dialog
					new AlertDialog.Builder(ActivityPayment.this)
					.setTitle("License Created")
					.setCancelable(false)
					.setMessage(message)
					.setPositiveButton(R.string.com_phonelicenses_ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							})
					.create()
					.show();
					break;
				default:
					Log.e(TAG, "RESULT_CODE_DEFAULT: "+message);
					showMessageDialog(R.string.com_phonelicenses_communication_error);
					break;
				}

			}
			
		}

		@Override
		public void onClick(View v) {
			Intent intent;
			if(v == button)
				if( acceptsConditions() && acceptsLicense() && acceptsRefundPolicy() )
				{
					intent = new Intent(ActivityPayment.this, ActivityAndroidMarketLicenseCheck.class);
					intent.setAction(Intent.ACTION_VIEW);
					startActivityForResult(intent, PhoneLicensesCodes.REQUEST_CODE_ANDROIDMARKET_PAYMENT);
				}
		}

		@Override
		public void onDestroy() {
			
		}
		
	}

}
